import axios from "axios";
import { showMessage } from "./status.ts"; // 状态码文件
import { ElMessage } from "element-plus";

// 设置接口超时时间
axios.defaults.timeout = 60000;
let data = localStorage.getItem("userInfo") || "";
let token: string = "";
if (data) {
  token = JSON.parse(data).token;
}

// 请求地址.env动态赋值的环境变量 方便管理
axios.defaults.baseURL = import.meta.env.VITE_SERVICE_API;

// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    data = localStorage.getItem("userInfo") || "";
    if (data) {
      token = JSON.parse(data).token;
    }
    // 配置请求头
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers["token"] = token;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  (response) => {
    // console.log(response.data);

    if (response.data.code == 403) {
      ElMessage.error(`${response.data.message},跳转登录页`);
      window.location.href = "/login";
    }
    return response.data;
  },
  (error) => {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      showMessage(response.status); // 传入响应码，匹配响应码对应信息
      return Promise.reject(response.data);
    } else {
      ElMessage.warning("网络连接异常,请稍后再试!");
    }
  }
);

// 封装 GET POST 请求并导出
export function request(url = "", params = {}, type = "POST") {
  //设置 url params type 的默认值
  return new Promise((resolve, reject) => {
    let promise;
    if (type.toUpperCase() === "GET") {
      promise = axios({
        url,
        params,
      });
    } else if (type.toUpperCase() === "POST") {
      promise = axios({
        method: "POST",
        url,
        data: params,
      });
    }
    //处理返回
    promise
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
